package com.snowflake.ecatalog.web.profile;

import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import com.snowflake.ecatalog.entity.GoodsCategory;
import com.snowflake.ecatalog.service.profile.GoodsCategoryService;
import com.snowflake.ecatalog.util.LoginUtil;

/**
 * 分类的Controller, 使用Restful风格的Urls:
 * 
 * List page : GET /itemize/ Create page : GET /itemize/create Create action :
 * POST /itemize/create Update page : GET /itemize/update/{id} Update action :
 * POST /itemize/update Delete action : GET /itemize/delete/{id}
 * 
 */
@Controller
@RequestMapping(value = "/goodsCategory")
public class GoodsCategoryController {

	private static final int PAGE_SIZE = 10;

	@Autowired
	private GoodsCategoryService goodsCategoryService;

	@RequestMapping(value = "")
	public String list(@RequestParam(value = "page", defaultValue = "1") int pageNumber, Model model,
			ServletRequest request, HttpSession session) {
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
		Long profileId = LoginUtil.getProfileIdFromSession(session);
		Page<GoodsCategory> itemizes = goodsCategoryService.getGoodsCategorys(profileId, searchParams, pageNumber,
				PAGE_SIZE);
		model.addAttribute("itemizes", itemizes);
		model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
		return "profile/goodsCategoryList";
	}

	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(Model model) {
		model.addAttribute("goodsCategory", new GoodsCategory());
		model.addAttribute("action", "create");
		return "profile/goodsCategoryForm";
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	public String create(@Valid GoodsCategory newGoodsCategory, RedirectAttributes redirectAttributes,
			ServletRequest request) {
		newGoodsCategory.setProfile(LoginUtil.getProfileFromRequest(request));
		goodsCategoryService.saveGoodsCategory(newGoodsCategory);
		redirectAttributes.addFlashAttribute("message", "创建商品分类成功");
		return "redirect:/goodsCategory";
	}

	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") Long id, Model model) {
		model.addAttribute("task", goodsCategoryService.getGoodsCategory(id));
		model.addAttribute("action", "update");
		return "profile/goodsCategoryForm";
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(@Valid @ModelAttribute("preloadGoodsCategory") GoodsCategory goodsCategory,
			RedirectAttributes redirectAttributes) {
		goodsCategoryService.updateGoodsCategory(goodsCategory);
		redirectAttributes.addFlashAttribute("message", "更新商品分类成功");
		return "redirect:/goodsCategory";
	}

	@RequestMapping(value = "enable/{id}")
	public String enable(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		goodsCategoryService.enableGoodsCategory(id);
		redirectAttributes.addFlashAttribute("message", "启用商品分类成功");
		return "redirect:/goodsCategory/";
	}

	@RequestMapping(value = "disable/{id}")
	public String disable(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		goodsCategoryService.disableGoodsCategory(id);
		redirectAttributes.addFlashAttribute("message", "禁用商品分类成功");
		return "redirect:/goodsCategory/";
	}

	@RequestMapping(value = "delete/{id}")
	public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		if (existGoodsInCategory(id)) {
			redirectAttributes.addFlashAttribute("message", "该商品分类下已关联商品，不能删除");
		} else {
			goodsCategoryService.deleteGoodsCategory(id);
			redirectAttributes.addFlashAttribute("message", "删除分类成功");
		}
		return "redirect:/goodsCategory/";
	}

	private boolean existGoodsInCategory(Long categoryId) {
		return goodsCategoryService.existGoodsInCategory(categoryId);
	}

	/**
	 * 使用@ModelAttribute, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出GoodsCategory对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此本方法在该方法中执行.
	 */
	@ModelAttribute("preloadGoodsCategory")
	public GoodsCategory getGoodsCategory(@RequestParam(value = "id", required = false) Long id) {
		if (id != null) {
			return goodsCategoryService.getGoodsCategory(id);
		}
		return null;
	}
}
